package com.caohx.bms.view;

import com.caohx.bms.pojo.BookCategory;
import com.caohx.bms.service.BookCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/book-category")
public class BookCategoryManage {

    @Autowired
    private BookCategoryService bookCategoryService;

    // 列表页面
    @GetMapping("/list")
    public String list(Model model,
                       @RequestParam(defaultValue = "0") int page,
                       @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<BookCategory> categories = bookCategoryService.findCategories(pageable); // 修改为实际方法名
        model.addAttribute("categories", categories);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", categories.getTotalPages());
        model.addAttribute("size", size); // 确保'size'也被传递到模板
        return "bookCategoryManage";
    }

    // 新增图书分类模态框
    @GetMapping("/add")
    public String addForm() {
        return "bookCategoryManage"; // 保持在列表页面，使用模态框处理新增
    }

    // 编辑图书分类模态框
    @GetMapping("/edit/{id}")
    public String editForm(@PathVariable Long id, Model model) {
        BookCategory category = bookCategoryService.get(id);
        model.addAttribute("category", category);
        return "bookCategoryManage"; // 保持在列表页面，使用模态框处理编辑
    }

    // 保存或更新图书分类
    @PostMapping("/save")
    public String save(@ModelAttribute BookCategory category) {

        bookCategoryService.edit(category);
        return "redirect:/book-category/list";
    }

    // 删除图书分类
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Long id) {
        bookCategoryService.delete(id);
        return "redirect:/book-category/list";
    }
}
